var express = require("express");
var router = express.Router();
const multer = require("multer");
const path = require("path");
const fs = require("fs");

const { RbacUserModel, PermissionModel, RoleModel, RolePermissionModel, UserRoleModel, YonghuUserModel, YonghuOrderModel, YonghuCouponModel, GoodsModel, HistoryModel } = require('../db');
const { generateTokens, verifyRefreshToken } = require('../utils/jwt');
const { sendResetPasswordCode } = require('../utils/emailService');
const authMiddleware = require('../middleware/auth');
const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require("alipay-sdk/lib/form").default

// 头像上传配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, "../upload/avatars");
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一的文件名
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    const ext = path.extname(file.originalname);
    cb(null, "avatar-" + uniqueSuffix + ext);
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 2 * 1024 * 1024, // 2MB
  },
  fileFilter: function (req, file, cb) {
    // 只允许图片格式
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(
      path.extname(file.originalname).toLowerCase()
    );
    const mimetype = allowedTypes.test(file.mimetype);

    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error("只允许上传图片格式的文件"));
    }
  },
});

// 凭证照片上传配置
const evidenceStorage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../upload/evidence');
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一的文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'evidence-' + uniqueSuffix + ext);
  }
});

const evidenceUpload = multer({
  storage: evidenceStorage,
  limits: {
    fileSize: 2 * 1024 * 1024 // 2MB
  },
  fileFilter: function (req, file, cb) {
    // 只允许图片格式
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    
    if (mimetype && extname) {
      return cb(null, true);
    } else {
      cb(new Error('只允许上传图片格式的文件'));
    }
  }
});

// 支付宝SDK配置
const alipaySdk = new AlipaySdk({
  appId: '9021000150653655', // 支付宝沙箱应用ID
  privateKey: 'MIIEpQIBAAKCAQEAxmwkL605qOGR3SQV/geOk7y0+CrNXWxiPwWpMLoWtgzo60cfVbGmoLahdnnrKbb07oCPEnJMGu7IRsimpf0cQkNcdsNqNPZLbMTFIWJSDL8yJGrp6I2rUajPlDyTa5v/YgKFKy1nMYM1QCdxvB++C9f3QqLMPaGpwfBFCswcj8R4E+9UDrZiJ2oSpR4a6Zas+CUMBhF8Z2tAgjHzLZfHf3LADsO+lqHRBkAQP4nQo0tWuQr5Jycfx614+Jhjx7AOIsjxL6uvlDXR1eCqrFqH53/6AKKlq52KjXVVxppvUhJqbwS0K5LyVP0jB4iUXJwBhtlpUeG+O3mkiNk5s7d/9QIDAQABAoIBAQDGMTxP1vISCwW8YpAJBhlW3hXREEfC+kCD/K6LekS3INwCLi9RVDpAq0tJ4OuQ5ituk0DVRw9Xk4y+jytN/y0bztbr1bMfJagfA8h32RJloxB9qcDsRZ2K2lhFE+CYiuAjUKsdfqNlpE4rP3ruUrJseBKFH8FsCi9bBRiheVFKE00uZCNU8/aQQb8iN3x80ETEgLkvLC5Ixi+9vn33yZCUIFDVl8LJz2//1xx05YIXHKRZs3kTLM3LbhgRigb+h3lbHt3rSnSRByEGNKjsof7oY/7Di3fMT6qqGOS3Rsd5FxJAmnTmplGQsWn5knUovjh00ZpxDc7vu0d+cYfhjTXdAoGBAONlFnu38o4G/bkJgdnAm13+2QWnu5GPPgeWIvWyvMby7llxblFCnrgqTuzmNIBQ0oe2V/CX1r9JmQqV/RXsvlSxUSybl72D7bKYIourqnd4JAsphdTs6DHC/HAMiuAvC3MiONKrwYH0QjBSGSF/BEw38yTRMcquGU204F2gOkv/AoGBAN9iCgYGDuOZvJS49zwcM87yBGayqUHNsq6Bk4+bYwAGrEtXb1qK7/ZxlN4FA6Vox5yimQ4sT35DkWZ/qbiLpQYWU9gDnT9udwTtsvycUb1CmusjfPWRt7OBSOXZ7WZhN6Q3yAPcx3Q82XT6nUiP/5iLbvFIpki6ym2u8fy8+cQLAoGANBrQuQ6gVK0DbGfiSiwZLcOcpPAXSbZB52ken6ASI6A8v1//gD08s0R2i1AAjbp3U0OUCPwx5+kMWWGe+Wwi/LMYv5jzfyiAyeCUYd63E+MCl1Ava2fRmL1uLJqjI9WD0SDxVkym7YkztXDKc2Nwb6qOW0xYFXIpOCYPF0UEtq8CgYEAhGuXyY5Z0S5Xjko/tZB6Xdk2JrMOhwWrQKtrkBvrCh7qkBca2a+3JH6cYyjRyoJcokv5M1+tGApx7TMMp2uQvhUKSumJlAql33QRQJJiGjGbqHx3HRPutCiV0Dvp8WD8HQs8NJ3yVsOjnSbbiiJiwEkX0Uzh1gd07KRiqxJTdZUCgYEAhYs7t8WJZOB5q/j/FDyYcpXrlXg6Eipf9oMDz96sXrRL5lSCoaCesJlnddsaEchseR/+r1Cnq4fxj/bt2gJThkEAkfCKqGI+bIiiiga8mqsbRi0OgOm5kX5JoAAxdiItruHk8OpWHDv0aN3BuPJ2mWKlarBCClayupS6d9UNGbQ=', // 应用私钥
  gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do', // 沙箱网关
  alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnwyMNzALTH99N6g9/+61b/MC2nCP/WL/XKUXOzmV/xbFisgwXaoV/1jUEiavq+Cr5eNNTTpApq7oKqwijRswB50uxMO1zI7m2Tgpv7XLTcVc1F2cjNLAlqbm0INueI98lNDvwD4QaFcs92LOHRClUOEFqRmk4Fsqk92B7YqlpfZpmvtOXICXzx2o9b0SA+xkFAl/CPunJGSsAOfVauzXCuEIRdcr2clGMEKjdTKwA7HjcBQcFbCDvPZK9w0jZm3lE84cmCNLFpH3AybmJwDPC3Ok7LC0DoxirVNEc62AobvVmZ6jCa5SeFKOnQrzZl5vc2NlUm7ewR4//UPFKwhNgQIDAQAB', // 支付宝公钥
  timeout: 30000, // 关键：延长超时时间30s
  signType: 'RSA2'
});

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

// ======rbac权限管理======

// ======用户管理路由======
// 获取用户列表
router.get("/user", async function (req, res, next) {
  try {
    const { page = 1, limit = 10, search = "" } = req.query;
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          // $options: 'i' 表示不区分大小写
          { userName: { $regex: search, $options: "i" } },
          { realName: { $regex: search, $options: "i" } },
          { email: { $regex: search, $options: "i" } },
        ],
      };
    }

    const users = await RbacUserModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ _id: 1 });

    const total = await RbacUserModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取用户列表成功",
      data: {
        list: users,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户列表失败",
      error: error.message,
    });
  }
});

// 获取用户角色列表
router.get("/user/:id/roles", async function (req, res, next) {
  try {
    const user = await RbacUserModel.findById(req.params.id);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 获取用户角色
    const userRoles = await UserRoleModel.find({ userId: req.params.id });
    const roleIds = userRoles.map((ur) => ur.roleId);
    const roles = await RoleModel.find({ _id: { $in: roleIds } });

    res.json({
      code: 200,
      message: "获取用户角色成功",
      data: {
        user,
        roles,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户角色失败",
      error: error.message,
    });
  }
});

// 新增用户
router.post("/user", async function (req, res, next) {
  try {
    const {
      userName,
      passWord,
      realName,
      email,
      phone,
      roleIds = [],
    } = req.body;

    // 检查用户名是否已存在
    const existingUser = await RbacUserModel.findOne({ userName });
    if (existingUser) {
      return res.status(400).json({
        code: 400,
        message: "用户名已存在",
      });
    }

    // 生成用户ID
    const userId = `user_${Date.now()}`;

    // 创建用户
    const user = new RbacUserModel({
      _id: userId,
      userName,
      passWord,
      realName,
      email,
      phone,
    });

    const savedUser = await user.save();

    // 分配角色
    if (roleIds.length > 0) {
      const userRoles = roleIds.map((roleId) => ({
        userId: savedUser._id,
        roleId,
      }));
      await UserRoleModel.insertMany(userRoles);
    }

    res.json({
      code: 200,
      message: "新增用户成功",
      data: savedUser,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "新增用户失败",
      error: error.message,
    });
  }
});

// 编辑用户
router.put("/user/:id", async function (req, res, next) {
  try {
    const { userName, realName, email, phone, status, roleIds = [] } = req.body;

    // 检查用户是否存在
    const user = await RbacUserModel.findById(req.params.id);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 检查用户名是否被其他用户使用
    if (userName && userName !== user.userName) {
      const existingUser = await RbacUserModel.findOne({
        userName,
        _id: { $ne: req.params.id },
      });
      if (existingUser) {
        return res.status(400).json({
          code: 400,
          message: "用户名已存在",
        });
      }
    }

    // 更新用户信息
    const updateData = {
      userName: userName || user.userName,
      realName: realName || user.realName,
      email: email || user.email,
      phone: phone || user.phone,
      status: status || user.status,
      updatedAt: new Date(),
    };

    const updatedUser = await RbacUserModel.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    );

    // 更新用户角色
    if (roleIds !== undefined) {
      // 删除原有角色
      await UserRoleModel.deleteMany({ userId: req.params.id });
      // 添加新角色
      if (roleIds.length > 0) {
        const userRoles = roleIds.map((roleId) => ({
          userId: req.params.id,
          roleId,
        }));
        await UserRoleModel.insertMany(userRoles);
      }
    }

    res.json({
      code: 200,
      message: "编辑用户成功",
      data: updatedUser,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "编辑用户失败",
      error: error.message,
    });
  }
});

// 删除用户
router.delete("/user/:id", async function (req, res, next) {
  try {
    const user = await RbacUserModel.findById(req.params.id);
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 删除用户
    await RbacUserModel.findByIdAndDelete(req.params.id);

    // 删除用户角色关联
    await UserRoleModel.deleteMany({ userId: req.params.id });

    res.json({
      code: 200,
      message: "删除用户成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除用户失败",
      error: error.message,
    });
  }
});

// ======角色管理路由======
// 获取角色列表
router.get("/role", async function (req, res, next) {
  try {
    const { page = 1, limit = 10, search = "" } = req.query;
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          { name: { $regex: search, $options: "i" } },
          { code: { $regex: search, $options: "i" } },
        ],
      };
    }

    const roles = await RoleModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ _id: 1 });

    const total = await RoleModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取角色列表成功",
      data: {
        list: roles,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取角色列表失败",
      error: error.message,
    });
  }
});

// 获取所有角色列表（用于选择）
router.get("/roles/all", async function (req, res, next) {
  try {
    const roles = await RoleModel.find({ status: "active" }).sort({ _id: 1 });

    res.json({
      code: 200,
      message: "获取角色列表成功",
      data: roles,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取角色列表失败",
      error: error.message,
    });
  }
});

// 获取角色权限树（用于权限分配）
router.get("/role/:id/permissions", async function (req, res, next) {
  try {
    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 获取角色已分配的权限ID列表
    const rolePermissions = await RolePermissionModel.find({
      roleId: req.params.id,
    });
    const assignedPermissionIds = rolePermissions.map((rp) =>
      rp.permissionId.toString()
    );

    // 获取所有权限并构建树形结构
    const permissions = await PermissionModel.find({ status: "active" }).sort({
      sort: 1,
    });

    const buildTree = (items, parentId = null) => {
      return items
        .filter((item) => {
          if (parentId === null) {
            return !item.parentId || item.parentId === "";
          }
          return item.parentId === parentId;
        })
        .map((item) => ({
          ...item.toObject(),
          children: buildTree(items, item._id),
        }));
    };

    const tree = buildTree(permissions);

    res.json({
      code: 200,
      message: "获取角色权限树成功",
      data: {
        role,
        permissionTree: tree,
        assignedPermissionIds,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取角色权限树失败",
      error: error.message,
    });
  }
});

// 获取角色用户列表
router.get("/role/:id/users", async function (req, res, next) {
  try {
    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 获取拥有该角色的用户
    const userRoles = await UserRoleModel.find({ roleId: req.params.id });
    const userIds = userRoles.map((ur) => ur.userId);
    const users = await RbacUserModel.find({ _id: { $in: userIds } });

    res.json({
      code: 200,
      message: "获取角色用户列表成功",
      data: {
        role,
        users,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取角色用户列表失败",
      error: error.message,
    });
  }
});

// 新增角色
router.post("/role", async function (req, res, next) {
  try {
    const { name, code, description, permissionIds = [] } = req.body;

    // 检查角色代码是否已存在
    const existingRole = await RoleModel.findOne({ code });
    if (existingRole) {
      return res.status(400).json({
        code: 400,
        message: "角色代码已存在",
      });
    }

    // 生成角色ID
    const roleId = `role_${Date.now()}`;

    // 创建角色
    const role = new RoleModel({
      _id: roleId,
      name,
      code,
      description,
    });

    const savedRole = await role.save();

    // 分配权限（只分配二级菜单权限）
    if (permissionIds.length > 0) {
      const validPermissionIds = [];
      for (const permissionId of permissionIds) {
        const permission = await PermissionModel.findById(permissionId);
        if (permission && permission.parentId) {
          validPermissionIds.push(permissionId);
        }
      }

      if (validPermissionIds.length > 0) {
        const rolePermissions = validPermissionIds.map((permissionId) => ({
          roleId: savedRole._id,
          permissionId,
        }));
        await RolePermissionModel.insertMany(rolePermissions);
      }
    }

    res.json({
      code: 200,
      message: "新增角色成功",
      data: savedRole,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "新增角色失败",
      error: error.message,
    });
  }
});

// 编辑角色
router.put("/role/:id", async function (req, res, next) {
  try {
    const { name, code, description, status, permissionIds = [] } = req.body;

    // 检查角色是否存在
    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 检查角色代码是否被其他角色使用
    if (code && code !== role.code) {
      const existingRole = await RoleModel.findOne({
        code,
        _id: { $ne: req.params.id },
      });
      if (existingRole) {
        return res.status(400).json({
          code: 400,
          message: "角色代码已存在",
        });
      }
    }

    // 更新角色信息
    const updateData = {
      name: name || role.name,
      code: code || role.code,
      description: description || role.description,
      status: status || role.status,
      updatedAt: new Date(),
    };

    const updatedRole = await RoleModel.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    );

    // 更新角色权限
    if (permissionIds !== undefined) {
      // 过滤掉一级菜单的权限ID，只保留二级菜单
      const validPermissionIds = [];
      for (const permissionId of permissionIds) {
        const permission = await PermissionModel.findById(permissionId);
        if (permission && permission.parentId) {
          validPermissionIds.push(permissionId);
        }
      }

      // 删除原有权限
      await RolePermissionModel.deleteMany({ roleId: req.params.id });

      // 添加新权限
      if (validPermissionIds.length > 0) {
        const rolePermissions = validPermissionIds.map((permissionId) => ({
          roleId: req.params.id,
          permissionId,
        }));
        await RolePermissionModel.insertMany(rolePermissions);
      }
    }

    res.json({
      code: 200,
      message: "编辑角色成功",
      data: updatedRole,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "编辑角色失败",
      error: error.message,
    });
  }
});

// 删除角色
router.delete("/role/:id", async function (req, res, next) {
  try {
    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 删除角色
    await RoleModel.findByIdAndDelete(req.params.id);

    // 删除角色权限关联
    await RolePermissionModel.deleteMany({ roleId: req.params.id });

    // 删除用户角色关联
    await UserRoleModel.deleteMany({ roleId: req.params.id });

    res.json({
      code: 200,
      message: "删除角色成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除角色失败",
      error: error.message,
    });
  }
});

// 分配角色权限
router.post("/role/:id/permissions", async function (req, res, next) {
  try {
    const { permissionIds = [] } = req.body;

    const role = await RoleModel.findById(req.params.id);
    if (!role) {
      return res.status(404).json({
        code: 404,
        message: "角色不存在",
      });
    }

    // 过滤掉一级菜单的权限ID，只保留二级菜单
    const validPermissionIds = [];
    for (const permissionId of permissionIds) {
      const permission = await PermissionModel.findById(permissionId);
      if (permission && permission.parentId) {
        validPermissionIds.push(permissionId);
      }
    }

    // 删除原有权限
    await RolePermissionModel.deleteMany({ roleId: req.params.id });

    // 添加新权限
    if (validPermissionIds.length > 0) {
      const rolePermissions = validPermissionIds.map((permissionId) => ({
        roleId: req.params.id,
        permissionId,
      }));
      await RolePermissionModel.insertMany(rolePermissions);
    }

    res.json({
      code: 200,
      message: "权限分配成功",
      data: {
        roleId: req.params.id,
        permissionIds: validPermissionIds,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "权限分配失败",
      error: error.message,
    });
  }
});

// ======权限管理路由======
// 获取所有权限列表（用于选择）
router.get("/permissions/all", async function (req, res, next) {
  try {
    // 获取一级和二级所有菜单用于树形选择器
    const permissions = await PermissionModel.find({ status: "active" }).sort({
      sort: 1,
    });
    res.json({
      code: 200,
      message: "获取权限列表成功",
      data: permissions,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取权限列表失败",
      error: error.message,
    });
  }
});

// 获取权限列表
router.get("/permission", async function (req, res, next) {
  try {
    const { page = 1, limit = 10, search = "", parentId } = req.query;
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          { name: { $regex: search, $options: "i" } },
          { code: { $regex: search, $options: "i" } },
        ],
      };
    }

    if (parentId) {
      query.parentId = parentId;
    }
    // 获取所有二级菜单，先按parentId排序，再按sort排序
    // 确保parentId存在
    // $ne:不等于
    // const permissions = await PermissionModel.find({ status: 'active',parentId:{$ne:null} }).sort({parentId:1,sort:1});
    const permissions = await PermissionModel.find({
      ...query,
      parentId: { $ne: null },
    })
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ parentId: 1, sort: 1 });

    const total = await PermissionModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取权限列表成功",
      data: {
        list: permissions,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取权限列表失败",
      error: error.message,
    });
  }
});

// 获取权限树形结构
router.get("/permission/tree", async function (req, res, next) {
  try {
    const permissions = await PermissionModel.find({ status: "active" }).sort({
      sort: 1,
    });

    // 构建树形结构
    const buildTree = (items, parentId = null) => {
      return items
        .filter((item) => {
          if (parentId === null) {
            return !item.parentId || item.parentId === "";
          }
          return item.parentId === parentId;
        })
        .map((item) => ({
          ...item.toObject(),
          children: buildTree(items, item._id),
          // 移除disabled属性，允许一级菜单可选择
        }));
    };

    const tree = buildTree(permissions);

    res.json({
      code: 200,
      message: "获取权限树成功",
      data: tree,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取权限树失败",
      error: error.message,
    });
  }
});

// 新增权限
router.post("/permission", async function (req, res, next) {
  try {
    const { name, code, description, parentId, path, icon, sort, isShow } =
      req.body;

    // 检查权限代码是否已存在
    const existingPermission = await PermissionModel.findOne({ code });
    if (existingPermission) {
      return res.status(400).json({
        code: 400,
        message: "权限代码已存在",
      });
    }

    // 检查权限路径是否已存在
    if (path) {
      const existingPath = await PermissionModel.findOne({ path });
      if (existingPath) {
        return res.status(400).json({
          code: 400,
          message: "权限路径已存在",
        });
      }
    }

    // 生成权限ID
    let permissionId;
    if (parentId) {
      // 二级菜单：parentId-number
      const childCount = await PermissionModel.countDocuments({ parentId });
      permissionId = `${parentId}-${childCount + 1}`;
    } else {
      // 一级菜单：数字
      const parentCount = await PermissionModel.countDocuments({
        parentId: null,
      });
      permissionId = `${parentCount + 1}`;
    }

    // 创建权限
    const permission = new PermissionModel({
      _id: permissionId,
      name,
      code,
      description,
      parentId,
      path,
      icon,
      sort: sort || 0,
      isShow: isShow || false,
    });

    const savedPermission = await permission.save();

    res.json({
      code: 200,
      message: "新增权限成功",
      data: savedPermission,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "新增权限失败",
      error: error.message,
    });
  }
});

// 编辑权限
router.put("/permission/:id", async function (req, res, next) {
  try {
    const {
      name,
      code,
      description,
      parentId,
      path,
      icon,
      sort,
      isShow,
      status,
    } = req.body;

    // 检查权限是否存在
    const permission = await PermissionModel.findById(req.params.id);
    if (!permission) {
      return res.status(404).json({
        code: 404,
        message: "权限不存在",
      });
    }

    // 检查权限代码是否被其他权限使用
    if (code && code !== permission.code) {
      const existingPermission = await PermissionModel.findOne({
        code,
        _id: { $ne: req.params.id },
      });
      if (existingPermission) {
        return res.status(400).json({
          code: 400,
          message: "权限代码已存在",
        });
      }
    }

    // 检查权限路径是否被其他权限使用
    if (path && path !== permission.path) {
      const existingPath = await PermissionModel.findOne({
        path,
        _id: { $ne: req.params.id },
      });
      if (existingPath) {
        return res.status(400).json({
          code: 400,
          message: "权限路径已存在",
        });
      }
    }

    // 更新权限信息
    const updateData = {
      name: name || permission.name,
      code: code || permission.code,
      description: description || permission.description,
      parentId: parentId || permission.parentId,
      path: path || permission.path,
      icon: icon || permission.icon,
      sort: sort !== undefined ? sort : permission.sort,
      isShow: isShow !== undefined ? isShow : permission.isShow,
      status: status || permission.status,
      updatedAt: new Date(),
    };

    const updatedPermission = await PermissionModel.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    );

    res.json({
      code: 200,
      message: "编辑权限成功",
      data: updatedPermission,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "编辑权限失败",
      error: error.message,
    });
  }
});

// 获取权限角色列表
router.get("/permission/:id/roles", async function (req, res, next) {
  try {
    const permission = await PermissionModel.findById(req.params.id);
    if (!permission) {
      return res.status(404).json({
        code: 404,
        message: "权限不存在",
      });
    }

    // 获取拥有该权限的角色
    const rolePermissions = await RolePermissionModel.find({
      permissionId: req.params.id,
    });
    const roleIds = rolePermissions.map((rp) => rp.roleId);
    const roles = await RoleModel.find({ _id: { $in: roleIds } });

    res.json({
      code: 200,
      message: "获取权限角色列表成功",
      data: {
        permission,
        roles,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取权限角色列表失败",
      error: error.message,
    });
  }
});

// 删除权限
router.delete("/permission/:id", async function (req, res, next) {
  try {
    const permission = await PermissionModel.findById(req.params.id);
    if (!permission) {
      return res.status(404).json({
        code: 404,
        message: "权限不存在",
      });
    }

    // 检查是否有子权限
    const childPermissions = await PermissionModel.find({
      parentId: req.params.id,
    });
    if (childPermissions.length > 0) {
      return res.status(400).json({
        code: 400,
        message: "该权限下有子权限，无法删除",
      });
    }

    // 删除权限
    await PermissionModel.findByIdAndDelete(req.params.id);

    // 删除角色权限关联
    await RolePermissionModel.deleteMany({ permissionId: req.params.id });

    res.json({
      code: 200,
      message: "删除权限成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除权限失败",
      error: error.message,
    });
  }
});

// ======用户登录和权限验证======
// 用户登录
router.post("/login", async function (req, res, next) {
  try {
    const { userName, passWord } = req.body;

    // 查找用户
    const user = await RbacUserModel.findOne({ userName, passWord });
    if (!user) {
      return res.status(401).json({
        code: 401,
        message: "用户名或密码错误",
      });
    }

    if (user.status !== "active") {
      return res.status(403).json({
        code: 403,
        message: "用户已被禁用",
      });
    }

    // 获取用户角色和权限
    const userRoles = await UserRoleModel.find({ userId: user._id });
    const roleIds = userRoles.map((ur) => ur.roleId);
    const roles = await RoleModel.find({ _id: { $in: roleIds } });

    const rolePermissions = await RolePermissionModel.find({
      roleId: { $in: roleIds },
    });
    const permissionIds = rolePermissions.map((rp) => rp.permissionId);
    const permissions = await PermissionModel.find({
      _id: { $in: permissionIds },
    });

    // 构建用户菜单权限（只包含二级菜单）
    const menuPermissions = permissions.filter((p) => p.parentId);

    // 生成双token，将用户信息、角色、权限编码到token中
    const userInfo = {
      id: user._id,
      userName: user.userName,
      realName: user.realName,
      email: user.email,
      phone: user.phone,
    };

    const tokens = generateTokens(userInfo, roles, menuPermissions);

    res.json({
      code: 200,
      message: "登录成功",
      data: {
        accessToken: tokens.accessToken,
        refreshToken: tokens.refreshToken,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "登录失败",
      error: error.message,
    });
  }
});

// 发送重置密码验证码
router.post("/send-reset-code", async function (req, res, next) {
  try {
    const { email } = req.body;

    if (!email) {
      return res.status(400).json({
        code: 400,
        message: "邮箱地址不能为空",
      });
    }

    // 查找用户
    const user = await RbacUserModel.findOne({ email });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "该邮箱地址未注册",
      });
    }

    // 生成6位数验证码
    const verificationCode = Math.floor(
      100000 + Math.random() * 900000
    ).toString();

    // 设置验证码过期时间（10分钟）
    const expiresAt = new Date(Date.now() + 10 * 60 * 1000);

    // 存储验证码到数据库
    await RbacUserModel.findByIdAndUpdate(user._id, {
      resetCode: verificationCode,
      resetCodeExpires: expiresAt,
    });

    // 发送邮件
    const emailResult = await sendResetPasswordCode(
      email,
      verificationCode,
      user.realName
    );

    // 统一返回格式，验证码放在data中
    res.json({
      code: 200,
      message: "验证码发送成功",
      data: {
        email: email,
        verificationCode: verificationCode,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "发送验证码失败",
      error: error.message,
    });
  }
});

// 重置密码
router.post("/reset-password", async function (req, res, next) {
  try {
    const { email, verificationCode, newPassword } = req.body;

    if (!email || !verificationCode || !newPassword) {
      return res.status(400).json({
        code: 400,
        message: "邮箱、验证码和新密码不能为空",
      });
    }

    // 查找用户
    const user = await RbacUserModel.findOne({ email });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 验证验证码
    if (!user.resetCode || user.resetCode !== verificationCode) {
      return res.status(400).json({
        code: 400,
        message: "验证码错误",
      });
    }

    // 检查验证码是否过期
    if (!user.resetCodeExpires || new Date() > user.resetCodeExpires) {
      return res.status(400).json({
        code: 400,
        message: "验证码已过期，请重新获取",
      });
    }

    // 检查新密码是否与旧密码相同
    if (newPassword === user.passWord) {
      return res.status(400).json({
        code: 400,
        message: "新密码与旧密码重复",
      });
    }

    // 更新密码并清除验证码
    await RbacUserModel.findByIdAndUpdate(user._id, {
      passWord: newPassword,
      resetCode: null,
      resetCodeExpires: null,
      updatedAt: new Date(),
    });

    res.json({
      code: 200,
      message: "密码重置成功",
      data: {
        email: email,
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "密码重置失败",
      error: error.message,
    });
  }
});

// 刷新访问令牌
router.post("/refresh-token", async function (req, res, next) {
  try {
    const { refreshToken } = req.body;

    if (!refreshToken) {
      return res.status(401).json({
        code: 401,
        message: "未提供刷新令牌",
      });
    }

    // 验证refresh token
    const decoded = verifyRefreshToken(refreshToken);

    // 查找用户确认用户仍然有效
    const user = await RbacUserModel.findById(decoded.userId);
    if (!user) {
      return res.status(401).json({
        code: 401,
        message: "用户不存在",
      });
    }

    if (user.status !== "active") {
      return res.status(403).json({
        code: 403,
        message: "用户已被禁用",
      });
    }

    // 获取用户角色和权限
    const userRoles = await UserRoleModel.find({ userId: user._id });
    const roleIds = userRoles.map((ur) => ur.roleId);
    const roles = await RoleModel.find({ _id: { $in: roleIds } });

    const rolePermissions = await RolePermissionModel.find({
      roleId: { $in: roleIds },
    });
    const permissionIds = rolePermissions.map((rp) => rp.permissionId);
    const permissions = await PermissionModel.find({
      _id: { $in: permissionIds },
    });

    // 构建用户菜单权限（只包含二级菜单）
    const menuPermissions = permissions.filter((p) => p.parentId);

    // 生成新的双token，将用户信息、角色、权限编码到token中
    const userInfo = {
      id: user._id,
      userName: user.userName,
      realName: user.realName,
      email: user.email,
      phone: user.phone,
    };

    const tokens = generateTokens(userInfo, roles, menuPermissions);

    res.json({
      code: 200,
      message: "刷新令牌成功",
      data: {
        accessToken: tokens.accessToken,
        refreshToken: tokens.refreshToken,
      },
    });
  } catch (error) {
    if (error.name === "TokenExpiredError") {
      return res.status(401).json({
        code: 401,
        message: "刷新令牌已过期，请重新登录",
      });
    }

    if (error.name === "JsonWebTokenError") {
      return res.status(401).json({
        code: 401,
        message: "刷新令牌无效",
      });
    }

    res.status(500).json({
      code: 500,
      message: "刷新令牌失败",
      error: error.message,
    });
  }
});








// ======我的======

// 获取用户列表
router.get("/yonghu", async function (req, res, next) {
  try {
    const { page = 1, limit = 10, search = "" } = req.query;
    const skip = (page - 1) * limit;

    let query = {};
    if (search) {
      query = {
        $or: [
          { username: { $regex: search, $options: "i" } },
          { nickname: { $regex: search, $options: "i" } },
          { email: { $regex: search, $options: "i" } },
          { phone: { $regex: search, $options: "i" } },
        ],
      };
    }

    const users = await YonghuUserModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ _id: 1 });

    const total = await YonghuUserModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取用户列表成功",
      data: {
        list: users,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户列表失败",
      error: error.message,
    });
  }
});

// 获取单个用户
router.get("/yonghu/:id", async function (req, res, next) {
  try {
    const user = await YonghuUserModel.findOne({ id: req.params.id }).sort({ _id: -1 });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 从独立的订单表中获取用户的订单
    const orders = await YonghuOrderModel.find({ userId: req.params.id }).sort({ _id: -1 });

    // 从独立的优惠券表中获取用户的优惠券
    const coupons = await YonghuCouponModel.find({ userId: req.params.id }).sort({ _id: -1 });

    // 构建返回数据，包含用户信息、订单信息和优惠券信息
    const userData = {
      user,
      orders,
      coupons
    };

    res.json({
      code: 200,
      message: "获取用户信息成功",
      data: userData,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户信息失败",
      error: error.message,
    });
  }
});

// 添加优惠券
router.post("/yonghu/:id/coupons", async function (req, res, next) {
  try {
    const { 
      couponId,
      name,
      type, 
      discount,
      minAmount,
      category,
      startTime,
      endTime,
      description,
    } = req.body;

    // 检查用户是否存在
    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 生成优惠券ID
    const couponDbId = `coupon_${Date.now()}`;
    const couponIdGenerated = couponId || `CPN${Date.now()}`;

    const coupon = new YonghuCouponModel({
      id: couponDbId,
      userId: req.params.id,
      couponId: couponIdGenerated,
      name,
      type,
      discount,
      minAmount: minAmount || 0,
      category,
      status: "可使用",
      startTime: new Date(startTime),
      endTime: new Date(endTime),
      description: description || "",
    });

    await coupon.save();

    res.json({
      code: 200,
      message: "添加优惠券成功",
      data: coupon,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "添加优惠券失败",
      error: error.message,
    });
    }
});

// 上传头像
router.post(
  "/yonghu/upload-avatar",
  upload.single("avatar"),
  async function (req, res, next) {
    try {
      if (!req.file) {
        return res.status(400).json({
          code: 400,
          message: "请选择要上传的图片",
        });
    }
    
      // 返回头像URL
      const avatarUrl = `/upload/avatars/${req.file.filename}`;

      res.json({
        code: 200,
        message: "头像上传成功",
        data: {
          avatarUrl: avatarUrl,
        },
      });
    } catch (error) {
      console.error("上传头像失败:", error);
      res.status(500).json({
        code: 500,
        message: "上传头像失败",
        error: error.message,
      });
    }
  }
);

// 上传凭证照片
router.post('/yonghu/upload-evidence', evidenceUpload.single('evidence'), async function(req, res, next) {
  try {
    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: '请选择要上传的图片'
      });
    }

    // 返回照片URL和其他信息
    const evidenceUrl = `/upload/evidence/${req.file.filename}`;
    
    res.json({
      code: 200,
      message: '凭证照片上传成功',
      data: {
        key: `evidence_${Date.now()}_${Math.random()}`,
        url: evidenceUrl,
        filename: req.file.filename,
        originalname: req.file.originalname,
        size: req.file.size,
        mimetype: req.file.mimetype
      }
    });
  } catch (error) {
    console.error('上传凭证照片失败:', error);
    res.status(500).json({
      code: 500,
      message: '上传凭证照片失败',
      error: error.message
    });
  }
});

// 创建支付宝支付订单
router.post('/yonghu/create-payment', async function(req, res, next) {
  try {
    const { orderId, amount, productNames, userId } = req.body;
    
    console.log('接收到的支付参数:', { orderId, amount, productNames, userId });
    
    if (!orderId || !amount || !userId) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数'
      });
    }

    // 生成商户订单号
    const outTradeNo = `ORDER_${userId}_${orderId}_${Date.now()}`;
    
    // 构建支付参数
    const bizContent = {
      outTradeNo: outTradeNo, //商户订单号
      productCode: 'FAST_INSTANT_TRADE_PAY', //产品码
      totalAmount: amount.toFixed(2), //总金额
      subject: typeof productNames === 'string' ? productNames : `订单${orderId}`, //订单标题
      body: `订单${orderId}的支付`,
      timeoutExpress: '30m', // 30分钟超时
    };

    // 使用AlipayFormData创建支付表单
    const formData = new AlipayFormData();
    formData.setMethod('get');
    formData.addField('bizContent', bizContent);
    formData.addField('returnUrl', 'http://localhost:5174/my/payment-success'); // 支付成功后的跳转URL
    formData.addField('notifyUrl', 'https://77361d7ffe18.ngrok-free.app/hy/yonghu/payment-callback'); // 支付宝回调URL
    
    // 生成支付URL
    const result = await alipaySdk.exec(
      'alipay.trade.page.pay',
      {}, // api 请求的参数（包含"公共请求参数"和"业务参数"）
      { formData: formData },
    );

    res.json({
      code: 200,
      message: '支付订单创建成功',
      data: {
        payUrl: result,
        outTradeNo: outTradeNo,
        orderId: orderId
      }
    });
  } catch (error) {
    console.error('创建支付订单失败:', error);
    res.status(500).json({
      code: 500,
      message: '创建支付订单失败',
      error: error.message
    });
  }
});


// 支付宝支付回调
router.post('/yonghu/payment-callback', async function(req, res, next) {
  try {
    const params = req.body;
    
    console.log('=== 支付宝回调开始 ===');
    console.log('回调参数:', params);
    
    // 验证支付宝回调签名
    const signVerified = alipaySdk.checkNotifySign(params);
    console.log('签名验证结果:', signVerified);
    
    if (!signVerified) {
      console.error('支付宝回调签名验证失败');
      return res.status(400).send('fail');
    }

    // 处理支付结果
    const { out_trade_no, trade_status, trade_no } = params;
    
    console.log('支付状态:', trade_status);
    console.log('商户订单号:', out_trade_no);
    console.log('支付宝交易号:', trade_no);
    
    if (trade_status === 'TRADE_SUCCESS') {
      console.log('支付成功，开始处理订单更新...');
      
      // 从outTradeNo中提取userId和orderId
      // outTradeNo格式: ORDER_${userId}_${orderId}_${timestamp}
      const orderMatch = out_trade_no.match(/^ORDER_(.+)_(.+)_\d+$/);
      if (!orderMatch) {
        console.error('无法从outTradeNo中提取userId和orderId:', out_trade_no);
        return res.status(400).send('fail');
      }
      
      const userId = orderMatch[1];
      const orderId = orderMatch[2];
      
      // 查找订单
      const order = await YonghuOrderModel.findOne({ 
        userId: userId,
        orderId: orderId 
      });
      
      if (!order) {
        console.error('未找到订单:', orderId, '用户ID:', userId);
        return res.status(404).send('fail');
      }
      
      // 更新订单状态
      order.status = '待发货';
      order.paymentMethod = '支付宝';
      order.tradeNo = trade_no;
      order.paidTime = new Date();
      order.outTradeNo = out_trade_no;
      order.updatedAt = new Date();
      
      // 保存更新
      await order.save();
      
      console.log('支付成功:', out_trade_no, '用户ID:', userId, '订单ID:', orderId);
    }

    res.send('success');
  } catch (error) {
    console.error('支付回调处理失败:', error);
    res.status(500).send('fail');
  }
});

// 前端主动查询并更新支付状态
router.post('/yonghu/check-payment-status', async function(req, res, next) {
  try {
    const { userId, orderId, outTradeNo } = req.body;
    
    if (!userId || !orderId || !outTradeNo) {
      return res.status(400).json({
        code: 400,
        message: '缺少必要参数'
      });
    }
    
    console.log('前端主动查询支付状态:', { userId, orderId, outTradeNo });
    
    // 先查找用户
    // 查找订单
    const order = await YonghuOrderModel.findOne({ 
      userId: userId,
      orderId: orderId 
    });
    
    if (!order) {
      console.error('未找到订单:', orderId, '用户ID:', userId);
      return res.status(404).json({
        code: 404,
        message: '订单不存在'
      });
    }
    
    console.log('当前订单状态:', order.status);
    
    // 如果订单状态还是"待付款"，则更新为"待发货"
    if (order.status === '待付款') {
      order.status = '待发货';
      order.paymentMethod = '支付宝';
      order.tradeNo = 'FRONTEND_' + Date.now();
      order.paidTime = new Date();
      order.outTradeNo = outTradeNo;
      order.updatedAt = new Date();
      
      await order.save();
      
      console.log('前端主动更新支付状态成功:', outTradeNo, '用户ID:', userId, '订单ID:', orderId);
      console.log('更新后的订单状态:', order.status);
    } else {
      console.log('订单状态已经是:', order.status, '，无需更新');
    }
    
    res.json({
      code: 200,
      message: '支付状态查询成功',
      data: {
        orderId: order.orderId,
        status: order.status,
        paymentMethod: order.paymentMethod,
        paidTime: order.paidTime,
        outTradeNo: order.outTradeNo
      }
    });
  } catch (error) {
    console.error('查询支付状态失败:', error);
    res.status(500).json({
      code: 500,
      message: '查询支付状态失败',
      error: error.message
    });
  }
});

// 修改用户个人信息
router.put("/yonghu/:id/profile", async function (req, res, next) {
  try {
    const { nickname, avatar, gender, phone, email } = req.body;

    // 参数验证
    if (!nickname || !phone || !email) {
      return res.status(400).json({
        code: 400,
        message: "昵称、手机号和邮箱为必填项",
      });
    }

    // 手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      return res.status(400).json({
        code: 400,
        message: "请输入正确的手机号格式",
      });
    }

    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return res.status(400).json({
        code: 400,
        message: "请输入正确的邮箱格式",
      });
    }

    const user = await YonghuUserModel.findOne({ id: req.params.id });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 检查手机号是否被其他用户使用
    const existingUserWithPhone = await YonghuUserModel.findOne({ 
      phone: phone, 
      id: { $ne: req.params.id } 
    });
    if (existingUserWithPhone) {
      return res.status(400).json({
        code: 400,
        message: "该手机号已被其他用户使用",
      });
    }

    // 检查邮箱是否被其他用户使用
    const existingUserWithEmail = await YonghuUserModel.findOne({ 
      email: email, 
      id: { $ne: req.params.id } 
    });
    if (existingUserWithEmail) {
      return res.status(400).json({
        code: 400,
        message: "该邮箱已被其他用户使用",
      });
    }

    // 更新个人信息
    const updateData = {
      nickname: nickname,
      avatar: avatar !== undefined ? avatar : user.avatar,
      gender: gender !== undefined ? gender : user.gender,
      phone: phone,
      email: email,
      updatedAt: new Date(),
    };

    const updatedUser = await YonghuUserModel.findOneAndUpdate(
      { id: req.params.id },
      updateData,
      { new: true } //返回更新后的用户
    );

    res.json({
      code: 200,
      message: "修改个人信息成功",
      data: {
        user: updatedUser
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "修改个人信息失败",
      error: error.message,
    });
  }
});

// 秒杀活动列表
router.get("/flash-sale/activities", (req, res) => {
  res.json({
    code: 200,
    data: {
      list: [
        {
          id: 1,
          name: "春季秒杀活动",
          time: "2021-03-02 ~ 2021-03-12",
          productCount: 10,
          status: "进行中",
          online: "上线",
        },
        {
          id: 2,
          name: "夏季秒杀活动",
          time: "2021-06-01 ~ 2021-06-10",
          productCount: 8,
          status: "未开始",
          online: "下线",
        },
        {
          id: 3,
          name: "双11大促",
          time: "2021-11-01 ~ 2021-11-11",
          productCount: 20,
          status: "已结束",
          online: "上线",
        },
      ],
      total: 3,
    },
  });
});
// 新建活动
router.post("/flash-sale/activities", (req, res) => {
  res.json({ code: 200, message: "新建成功" });
});
// 编辑活动
router.put("/flash-sale/activities/:id", (req, res) => {
  res.json({ code: 200, message: "编辑成功" });
});
// 删除活动
router.delete("/flash-sale/activities/:id", (req, res) => {
  res.json({ code: 200, message: "删除成功" });
});
// 下线活动
router.post("/flash-sale/activities/:id/offline", (req, res) => {
  res.json({ code: 200, message: "下线成功" });
});

// ======订单管理======

// 获取订单列表
router.get("/orders", async function (req, res, next) {
  try {
    const { 
      page = 1, 
      limit = 10, 
      status, 
      search = "",
      startDate,
      endDate,
      minAmount,
      maxAmount,
      userId
    } = req.query;
    const skip = (page - 1) * limit;

    // 构建查询条件
    let query = {};
    
    // 用户ID筛选
    if (userId) {
      query.userId = userId;
    }
    
    // 状态筛选
    if (status) {
      query.status = status;
    }
    
    // 搜索功能 - 订单号、商品名称、收货地址
    if (search) {
      query.$or = [
        { orderId: { $regex: search, $options: 'i' } },
        { deliveryAddress: { $regex: search, $options: 'i' } },
        { caption: { $regex: search, $options: 'i' } }
      ];
    }
    
    // 日期范围筛选
    if (startDate || endDate) {
      query.orderTime = {};
      if (startDate) {
        query.orderTime.$gte = new Date(startDate);
      }
      if (endDate) {
        query.orderTime.$lte = new Date(endDate);
      }
    }
    
    // 金额范围筛选
    if (minAmount || maxAmount) {
      query.totalPrice = {};
      if (minAmount) {
        query.totalPrice.$gte = parseFloat(minAmount);
      }
      if (maxAmount) {
        query.totalPrice.$lte = parseFloat(maxAmount);
      }
    }

    // 获取订单列表
    const orders = await YonghuOrderModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ orderTime: -1 });

    // 获取总数
    const total = await YonghuOrderModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取订单列表成功",
      data: {
        list: orders,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit))
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取订单列表失败",
      error: error.message,
    });
  }
});

// 获取订单详情
router.get("/orders/:orderId", async function (req, res, next) {
  try {
    const order = await YonghuOrderModel.findOne({ orderId: req.params.orderId });
    
    if (!order) {
      return res.status(404).json({
        code: 404,
        message: "订单不存在",
      });
    }

    res.json({
      code: 200,
      message: "获取订单详情成功",
      data: order,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取订单详情失败",
      error: error.message,
    });
  }
});

// 更新订单状态
router.put("/orders/:orderId/status", async function (req, res, next) {
  try {
    const {
      status,
      driverName, 
      driverPhone, 
      plateNumber, 
      remark, 
      logistics,
      shipTime 
    } = req.body;

    // 验证状态值
    const validStatuses = [
      "待付款",
      "待发货",
      "待提货",
      "待评价",
      "退款中",
      "已退款",
    ];
    if (!validStatuses.includes(status)) {
        return res.status(400).json({
          code: 400,
        message: "无效的订单状态，支持的状态：" + validStatuses.join("、"),
      });
    }

    const order = await YonghuOrderModel.findOne({ orderId: req.params.orderId });
    
    if (!order) {
      return res.status(404).json({
        code: 404,
        message: "订单不存在",
      });
    }

    // 更新订单状态
    order.status = status;

    // 如果状态变为待提货，生成提货码
    if (status === "待提货") {
      // 生成6位随机数字提货码
      const pickupCode = Math.floor(100000 + Math.random() * 900000).toString();
      order.pickupCode = pickupCode;
    }

    // 根据状态更新相关时间
    if (status === "待评价") {
      order.completedTime = new Date();
      }

    order.updatedAt = new Date();

    await order.save();

    // 如果是发货操作，同时更新历史记录
    if (status === "待提货" && (driverName || driverPhone || plateNumber)) {
      try {
        // 查找现有历史记录
        let history = await HistoryModel.findOne({ orderId: req.params.orderId });
        
        if (history) {
          // 更新现有的发货时间点
          const shipTimeIndex = history.historyList.findIndex(item => item.type === '发货时间');
          
          if (shipTimeIndex !== -1) {
            // 更新现有的发货时间记录
            history.historyList[shipTimeIndex] = {
              type: '发货时间',
              time: shipTime || new Date().toISOString(),
              driverName: driverName || '',
              driverPhone: driverPhone || '',
              plateNumber: plateNumber || '',
              remark: remark || '',
              logistics: logistics || ''
            };
          } else {
            // 如果没有找到发货时间点，添加一个新的
            history.historyList.push({
              type: '发货时间',
              time: shipTime || new Date().toISOString(),
              driverName: driverName || '',
              driverPhone: driverPhone || '',
              plateNumber: plateNumber || '',
              remark: remark || '',
              logistics: logistics || ''
            });
          }
          
          history.updatedAt = new Date();
          await history.save();
        } else {
          // 创建新的历史记录，包含完整的historyList结构
          const historyList = [
            {
              type: '下单时间',
              time: order.orderTime || new Date().toISOString()
            },
            {
              type: '发货时间',
              time: shipTime || new Date().toISOString(),
              driverName: driverName || '',
              driverPhone: driverPhone || '',
              plateNumber: plateNumber || '',
              remark: remark || '',
              logistics: logistics || ''
            },
            {
              type: '申请退款时间',
              time: '-'
            },
            {
              type: '审核时间',
              time: '-'
            }
          ];
          
          history = new HistoryModel({
            id: `history_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
            userId: order.userId,
            orderId: req.params.orderId,
            historyList: historyList,
            createdAt: new Date(),
            updatedAt: new Date()
          });
          await history.save();
        }
      } catch (historyError) {
        console.error('历史记录更新失败:', historyError);
        // 历史记录失败不影响订单状态更新
      }
    }

    res.json({
      code: 200,
      message: "订单状态修改成功",
      data: {
        orderId: order.orderId,
        status: order.status,
        completedTime: order.completedTime,
        pickupCode: order.pickupCode, // 返回提货码
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "修改订单状态失败",
      error: error.message,
    });
  }
});


// ======优惠券管理======

// 获取优惠券列表
router.get("/coupons", async function (req, res, next) {
  try {
    const {
      page = 1, 
      limit = 10, 
      status, 
      type,
      category,
      search = "",
      userId
    } = req.query;
    const skip = (page - 1) * limit;

    // 构建查询条件
    let query = {};
    
    // 用户ID筛选
    if (userId) {
      query.userId = userId;
    }
    
    // 状态筛选
    if (status) {
      query.status = status;
    }
    
    // 类型筛选
    if (type) {
      query.type = type;
    }

    // 分类筛选
    if (category) {
      query.category = category;
    }
    
    // 搜索功能
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } },
        { couponId: { $regex: search, $options: 'i' } }
      ];
    }

    // 获取优惠券列表
    const coupons = await YonghuCouponModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });

    // 获取总数
    const total = await YonghuCouponModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取优惠券列表成功",
      data: {
        list: coupons,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit))
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取优惠券列表失败",
      error: error.message,
    });
  }
});

// 获取优惠券详情
router.get("/coupons/:couponId", async function (req, res, next) {
    try {
    const coupon = await YonghuCouponModel.findOne({ couponId: req.params.couponId });

      if (!coupon) {
        return res.status(404).json({
          code: 404,
          message: "优惠券不存在",
        });
      }

      res.json({
        code: 200,
      message: "获取优惠券详情成功",
      data: coupon,
      });
    } catch (error) {
      res.status(500).json({
        code: 500,
      message: "获取优惠券详情失败",
        error: error.message,
      });
    }
});

// 更新优惠券状态
router.put("/coupons/:couponId/status", async function (req, res, next) {
    try {
      const { status } = req.body;

      // 验证状态值
      const validStatuses = ["可使用", "已使用", "已过期"];
      if (!validStatuses.includes(status)) {
        return res.status(400).json({
          code: 400,
          message: "无效的优惠券状态，支持的状态：" + validStatuses.join("、"),
        });
      }

    const coupon = await YonghuCouponModel.findOne({ couponId: req.params.couponId });
      
      if (!coupon) {
        return res.status(404).json({
          code: 404,
          message: "优惠券不存在",
        });
      }

      // 更新优惠券状态
      coupon.status = status;
      coupon.updatedAt = new Date();

      await coupon.save();

      res.json({
        code: 200,
        message: "优惠券状态修改成功",
        data: {
        couponId: coupon.couponId,
          name: coupon.name,
          status: coupon.status,
          type: coupon.type,
          discount: coupon.discount,
        },
      });
    } catch (error) {
      res.status(500).json({
        code: 500,
        message: "修改优惠券状态失败",
        error: error.message,
      });
    }
});

// 删除优惠券
router.delete("/coupons/:couponId", async function (req, res, next) {
  try {
    const coupon = await YonghuCouponModel.findOneAndDelete({ couponId: req.params.couponId });

    if (!coupon) {
      return res.status(404).json({
        code: 404,
        message: "优惠券不存在",
      });
    }

    res.json({
      code: 200,
      message: "删除优惠券成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除优惠券失败",
      error: error.message,
    });
  }
});

// ======创建订单======

// 创建订单
router.post("/create-order", async function (req, res, next) {
  try {
    const {
      userId,
      products,
      paymentMethod = "支付宝",
      deliveryAddress = "保定市莲池区南大园乡河北科技学院",
      caption = ""
    } = req.body;

    // 验证必填参数
    if (!userId || !products || products.length === 0) {
      return res.status(400).json({
        code: 400,
        message: "用户ID和商品信息为必填项",
      });
    }

    // 检查用户是否存在
    const user = await YonghuUserModel.findOne({ id: userId });
    if (!user) {
      return res.status(404).json({
        code: 404,
        message: "用户不存在",
      });
    }

    // 计算订单总数量和总价格
    const totalQuantity = products.reduce((sum, product) => sum + product.quantity, 0);
    const totalPrice = products.reduce((sum, product) => sum + (product.price * product.quantity), 0);

    // 生成订单ID
    const orderId = `ORD${Date.now()}`;
    const orderDbId = `order_${Date.now()}`;

    const order = new YonghuOrderModel({
      id: orderDbId,
      userId: userId,
      orderId: orderId,
      products: products.map(product => ({
        productId: product.productId,
        quantity: product.quantity
      })),
      totalQuantity,
      totalPrice,
      status: "待付款",
      orderTime: new Date(),
      paymentMethod: paymentMethod,
      deliveryAddress: deliveryAddress,
      pickupCode: "",
      completedTime: null,
      refundReason: "",
      refundAmount: 0,
      refundTime: null,
      caption: caption,
    });

    await order.save();

    res.json({
      code: 200,
      message: "创建订单成功",
      data: {
        orderId: order.orderId,
        totalPrice: order.totalPrice,
        status: order.status
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "创建订单失败",
      error: error.message,
    });
  }
});

// ======商品管理======

// 获取商品列表
router.get("/products", async function (req, res, next) {
  try {
    const {
      page = 1, 
      limit = 10, 
      category,
      search = "",
    } = req.query;
    const skip = (page - 1) * limit;

    // 构建查询条件
    let query = {};
    
    // 分类筛选
    if (category) {
      query.category = category;
    }

    // 搜索功能 - 商品标题、描述
    if (search) {
      query.$or = [
        { title: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } }
      ];
    }

    // 获取商品列表
    const products = await GoodsModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });

    // 获取总数
    const total = await GoodsModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取商品列表成功",
      data: {
        list: products,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit))
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取商品列表失败",
      error: error.message,
    });
  }
});

// 获取单个商品详情
router.get("/getproduct/:productId", async function (req, res, next) {
  try {
    const product = await GoodsModel.findOne({ id: req.params.productId });

    if (!product) {
      return res.status(404).json({
        code: 404,
        message: "商品不存在",
      });
    }

    res.json({
      code: 200,
      message: "获取商品详情成功",
      data: product,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取商品详情失败",
      error: error.message,
    });
  }
});

// 创建商品
router.post("/products", async function (req, res, next) {
  try {
    const {
      title,
      description,
      currentPrice,
      originalPrice,
      category,
      stock,
      image,
      unit
    } = req.body;

    // 验证必填参数
    if (!title || !currentPrice || !category) {
      return res.status(400).json({
        code: 400,
        message: "商品标题、价格和分类为必填项",
      });
    }

    // 验证价格
    if (isNaN(currentPrice) || parseFloat(currentPrice) < 0) {
      return res.status(400).json({
        code: 400,
        message: "商品价格必须为正数",
      });
    }

    // 生成商品ID
    const productId = `PROD${Date.now()}`;

    const product = new GoodsModel({
      id: productId,
      title: title,
      image: image || "",
      category: category,
      tags: [],
      activity: [],
      currentPrice: parseFloat(currentPrice),
      originalPrice: parseFloat(originalPrice) || parseFloat(currentPrice),
      stock: parseInt(stock) || 0,
      sales: 0,
      description: description || "",
      unit: unit || "",
      createdAt: new Date(),
      updatedAt: new Date()
    });

    await product.save();

    res.json({
      code: 200,
      message: "创建商品成功",
      data: {
        id: product.id,
        title: product.title,
        currentPrice: product.currentPrice
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "创建商品失败",
      error: error.message,
    });
  }
});

// 更新商品
router.put("/products/:productId", async function (req, res, next) {
    try {
    const {
      title,
      description,
      currentPrice,
      originalPrice,
      category,
      stock,
      image,
      unit
    } = req.body;

    const product = await GoodsModel.findOne({ id: req.params.productId });
    
    if (!product) {
      return res.status(404).json({
        code: 404,
        message: "商品不存在",
      });
    }

    // 更新商品信息
    if (title !== undefined) product.title = title;
    if (description !== undefined) product.description = description;
    if (currentPrice !== undefined) {
      if (isNaN(currentPrice) || parseFloat(currentPrice) < 0) {
        return res.status(400).json({
          code: 400,
          message: "商品价格必须为正数",
        });
      }
      product.currentPrice = parseFloat(currentPrice);
    }
    if (originalPrice !== undefined) {
      product.originalPrice = parseFloat(originalPrice);
    }
    if (category !== undefined) product.category = category;
    if (stock !== undefined) product.stock = parseInt(stock);
    if (image !== undefined) product.image = image;
    if (unit !== undefined) product.unit = unit;
    
    product.updatedAt = new Date();

    await product.save();

      res.json({
        code: 200,
      message: "更新商品成功",
        data: {
        id: product.id,
        title: product.title,
        currentPrice: product.currentPrice
      }
      });
    } catch (error) {
      res.status(500).json({
        code: 500,
      message: "更新商品失败",
        error: error.message,
      });
    }
});

// 删除商品
router.delete("/products/:productId", async function (req, res, next) {
  try {
    const product = await GoodsModel.findOneAndDelete({ id: req.params.productId });

    if (!product) {
      return res.status(404).json({
        code: 404,
        message: "商品不存在",
      });
    }
    
    res.json({
      code: 200,
      message: "删除商品成功",
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除商品失败",
      error: error.message,
    });
  }
});

// ======订单历史记录管理======

// 获取订单历史记录列表
router.get("/order-history", async function (req, res, next) {
  try {
    const { 
      page = 1, 
      limit = 10, 
      userId,
      orderId,
      search = ""
    } = req.query;
    const skip = (page - 1) * limit;
      
    // 构建查询条件
    let query = {};
    
    // 用户ID筛选
    if (userId) {
      query.userId = userId;
    }

    // 订单号筛选
    if (orderId) {
      query.orderId = { $regex: orderId, $options: 'i' };
      }
      
    // 搜索功能 - 订单号、用户ID
    if (search) {
      query.$or = [
        { orderId: { $regex: search, $options: 'i' } },
        { userId: { $regex: search, $options: 'i' } }
      ];
    }

    // 获取订单历史记录列表
    const historyList = await HistoryModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });
    
    // 获取总数
    const total = await HistoryModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取订单历史记录成功",
      data: {
        list: historyList,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit))
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取订单历史记录失败",
      error: error.message,
    });
  }
});

// 获取单个订单历史记录详情
router.get("/order-history/:orderId", async function (req, res, next) {
  try {
    const history = await HistoryModel.findOne({ orderId: req.params.orderId });
    
    if (!history) {
      return res.status(404).json({
        code: 404,
        message: "订单历史记录不存在",
      });
    }
    
    res.json({
      code: 200,
      message: "获取订单历史记录详情成功",
      data: history,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取订单历史记录详情失败",
      error: error.message,
    });
  }
});
      
// 根据用户ID获取订单历史记录
router.get("/user/:userId/order-history", async function (req, res, next) {
  try {
    const { 
      page = 1, 
      limit = 10,
      orderId
    } = req.query;
    const skip = (page - 1) * limit;
      
    // 构建查询条件
    let query = { userId: req.params.userId };
      
    // 订单号筛选
    if (orderId) {
      query.orderId = { $regex: orderId, $options: 'i' };
      }
      
    // 获取用户订单历史记录
    const historyList = await HistoryModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });
      
    // 获取总数
    const total = await HistoryModel.countDocuments(query);

    res.json({
      code: 200,
      message: "获取用户订单历史记录成功",
      data: {
        list: historyList,
        total,
        page: parseInt(page),
        limit: parseInt(limit),
        totalPages: Math.ceil(total / parseInt(limit))
      },
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取用户订单历史记录失败",
      error: error.message,
    });
  }
});

// 创建订单历史记录
router.post("/order-history", async function (req, res, next) {
  try {
    const {
      userId,
      orderId,
      historyList
    } = req.body;

    // 验证必填参数
    if (!userId || !orderId || !historyList) {
      return res.status(400).json({
        code: 400,
        message: "用户ID、订单号和历史记录列表为必填项",
        });
      }

    // 检查订单历史记录是否已存在
    const existingHistory = await HistoryModel.findOne({ orderId });
    if (existingHistory) {
      return res.status(400).json({
        code: 400,
        message: "该订单的历史记录已存在",
      });
    }
    
    const history = new HistoryModel({
      userId,
      orderId,
      historyList,
      createdAt: new Date(),
      updatedAt: new Date()
    });

    await history.save();

      res.json({
        code: 200,
      message: "创建订单历史记录成功",
        data: {
        orderId: history.orderId,
        userId: history.userId
      }
      });
    } catch (error) {
      res.status(500).json({
        code: 500,
      message: "创建订单历史记录失败",
        error: error.message,
      });
    }
});
    
// 更新单个订单历史记录
router.put("/order-history/:orderId", async function (req, res, next) {
    try {
    const {
      historyList
    } = req.body;

    const history = await HistoryModel.findOne({ orderId: req.params.orderId });
    
    if (!history) {
      return res.status(404).json({
        code: 404,
        message: "订单历史记录不存在",
      });
    }

    // 更新历史记录
    if (historyList) {
      history.historyList = historyList;
      }

    history.updatedAt = new Date();

    await history.save();
    
    res.json({
      code: 200,
      message: "更新订单历史记录成功",
      data: {
        orderId: history.orderId,
        userId: history.userId
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "更新订单历史记录失败",
        error: error.message,
    });
  }
});

// 更新多个订单历史记录
router.put("/order-history", async function (req, res, next) {
  try {
    const {
      updates // 格式: [{orderId: "xxx", historyList: [...], append: false}, ...]
    } = req.body;
    
    if (!updates || !Array.isArray(updates)) {
      return res.status(400).json({
        code: 400,
        message: "缺少更新数据或格式错误",
      });
    }
    
    const results = [];
    const errors = [];

    for (const update of updates) {
      try {
        const { orderId, historyList, singleRecord, append = false } = update;
        
        if (!orderId) {
          errors.push({ orderId: 'unknown', error: '缺少订单ID' });
          continue;
        }

        const history = await HistoryModel.findOne({ orderId });
    
        if (!history) {
          errors.push({ orderId, error: '订单历史记录不存在' });
          continue;
        }

        // 更新历史记录
        if (singleRecord && append) {
          // 追加单个记录
          history.historyList.push(singleRecord);
        } else if (historyList && append) {
          // 追加多个记录
          history.historyList = [...history.historyList, ...historyList];
        } else if (historyList) {
          // 替换整个历史记录列表
          history.historyList = historyList;
        } else if (singleRecord) {
          // 替换为单个记录
          history.historyList = [singleRecord];
    } else {
          errors.push({ orderId, error: '缺少历史记录数据' });
          continue;
        }

        history.updatedAt = new Date();
        await history.save();

        results.push({
          orderId,
          success: true,
          message: '更新成功'
        });
      } catch (error) {
        errors.push({ 
          orderId: update.orderId || 'unknown', 
          error: error.message 
        });
      }
    }
    
    res.json({
      code: 200,
      message: "批量更新订单历史记录完成",
      data: {
        results,
        errors,
        total: updates.length,
        success: results.length,
        failed: errors.length
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "批量更新订单历史记录失败",
      error: error.message,
    });
  }
});

// 删除订单历史记录
router.delete("/order-history/:orderId", async function (req, res, next) {
  try {
    const history = await HistoryModel.findOneAndDelete({ orderId: req.params.orderId });

    if (!history) {
      return res.status(404).json({
        code: 404,
        message: "订单历史记录不存在",
      });
    }

      res.json({
        code: 200,
      message: "删除订单历史记录成功",
      });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除订单历史记录失败",
      error: error.message,
    });
  }
});

// ======售后管理======

// 获取售后列表
router.get("/after-sales", async function (req, res, next) {
  try {
    const { 
      page = 1, 
      limit = 10, 
      orderId, 
      productStatus,
      startDate,
      endDate
    } = req.query;
    const skip = (page - 1) * limit;

    // 构建查询条件
    let query = {};
    
    // 订单号筛选
    if (orderId) {
      query.orderId = { $regex: orderId, $options: 'i' };
    }
    
    // 商品状态筛选（订单状态）
    if (productStatus) {
      query.status = productStatus;
    }
    
    // 日期范围筛选
    if (startDate || endDate) {
      query.orderTime = {};
      if (startDate) {
        query.orderTime.$gte = new Date(startDate);
      }
      if (endDate) {
        query.orderTime.$lte = new Date(endDate);
      }
    }

    // 只查询有退款申请的订单
    query.status = { $in: ['退款中', '已退款', '退款失败'] };

    // 获取订单列表
    const orders = await YonghuOrderModel.find(query)
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ orderTime: -1 });

    // 获取总数
    const total = await YonghuOrderModel.countDocuments(query);

    // 获取历史记录
    const orderIds = orders.map(order => order.orderId);
    const histories = await HistoryModel.find({ orderId: { $in: orderIds } });

    // 获取所有商品信息
    const productIds = [];
    orders.forEach(order => {
      if (order.products && Array.isArray(order.products)) {
        order.products.forEach(product => {
          if (product.productId) {
            productIds.push(product.productId);
          }
        });
      }
    });
    
    const goods = await GoodsModel.find({ id: { $in: productIds } });
    
    const goodsMap = {};
    goods.forEach(good => {
      goodsMap[good.id] = good;
    });

    // 合并订单和历史记录数据
    const afterSalesList = orders.map(order => {
      const history = histories.find(h => h.orderId === order.orderId);
      const refundHistory = history?.historyList?.find(h => h.type === '申请退款时间');
      const auditHistory = history?.historyList?.find(h => h.type === '审核时间');
      
      // 计算退款金额
      let refundAmount = 0;
      if (order.products && Array.isArray(order.products)) {
        order.products.forEach(product => {
          const good = goodsMap[product.productId];
          if (good && good.currentPrice && product.quantity) {
            const productTotal = good.currentPrice * product.quantity;
            refundAmount += productTotal;
          }
        });
      }
      
      return {
        id: order.id,
        orderId: order.orderId,
        userId: order.userId,
        userName: order.userId, // 可以根据需要获取用户名
        refundTime: refundHistory?.time || order.orderTime,
        refundAmount: refundAmount,
        productStatus: order.status,
        refundReason: refundHistory?.reason || '申请退款',
        auditTime: auditHistory?.time,
        auditRemark: auditHistory?.remark,
        auditor: auditHistory?.auditor,
        evidencePhotos: refundHistory?.evidencePhotos || [], // 添加退款凭证图片
        totalQuantity: order.totalQuantity,
        orderTime: order.orderTime,
        deliveryAddress: order.deliveryAddress,
        caption: order.caption,
        createdAt: order.createdAt,
        updatedAt: order.updatedAt
      };
    });

    res.json({
      code: 200,
      message: "获取售后列表成功",
      data: afterSalesList,
      total,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(total / parseInt(limit))
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取售后列表失败",
      error: error.message,
    });
  }
});

// 更新售后状态
router.put("/after-sales/:id/status", async function (req, res, next) {
  try {
    const { action, auditRemark, auditor } = req.body; // action: 'approve' 或 'reject'
    let currentAuditor = auditor || '管理员'; // 保证全局有定义

    // 验证操作类型
    if (!['approve', 'reject'].includes(action)) {
        return res.status(400).json({
          code: 400,
        message: "无效的操作类型，支持的操作：approve（通过）、reject（驳回）",
      });
    }

    // 先尝试通过id查询，如果找不到再通过orderId查询
    let order = await YonghuOrderModel.findOne({ id: req.params.id });
    
    // 如果通过id找不到，尝试通过orderId查询
    if (!order) {
      order = await YonghuOrderModel.findOne({ orderId: req.params.id });
    }
      
      if (!order) {
        return res.status(404).json({
          code: 404,
          message: "订单不存在",
        });
      }

    // 根据操作类型设置订单状态
    let newStatus;
    let auditMessage;
    
    if (action === 'approve') {
      newStatus = '已退款';
      auditMessage = auditRemark || '退款申请已通过';
    } else {
      newStatus = '退款失败';
      auditMessage = auditRemark || '退款申请已驳回';
    }

    // 更新订单状态
    order.status = newStatus;
      order.updatedAt = new Date();
      await order.save();

    // 更新历史记录
    try {
      let history = await HistoryModel.findOne({ orderId: order.orderId });
      currentAuditor = auditor || '管理员'; // 只赋值，不重新声明
      
      if (history) {
        // 更新审核时间记录
        const auditTimeIndex = history.historyList.findIndex(item => item.type === '审核时间');
        const currentTime = new Date().toISOString();
        
        if (auditTimeIndex !== -1) {
          // 更新现有的审核时间记录
          history.historyList[auditTimeIndex] = {
            type: '审核时间',
            time: currentTime,
            remark: auditMessage,
            auditor: currentAuditor,
            action: action
          };
        } else {
          // 如果没有找到审核时间点，添加一个新的
          history.historyList.push({
            type: '审核时间',
            time: currentTime,
            remark: auditMessage,
            auditor: currentAuditor,
            action: action
          });
        }
        
        history.updatedAt = new Date();
        await history.save();
      } else {
        // 如果历史记录不存在，创建一个新的
        const historyList = [
          {
            type: '下单时间',
            time: order.orderTime || new Date().toISOString()
          },
          {
            type: '申请退款时间',
            time: order.orderTime || new Date().toISOString(),
            reason: '申请退款'
          },
          {
            type: '审核时间',
            time: new Date().toISOString(),
            remark: auditMessage,
            auditor: currentAuditor,
            action: action
          }
        ];
        
        history = new HistoryModel({
          id: `history_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          userId: order.userId,
          orderId: order.orderId,
          historyList: historyList,
          createdAt: new Date(),
          updatedAt: new Date()
        });
        await history.save();
      }
    } catch (historyError) {
      console.error('历史记录更新失败:', historyError);
      // 历史记录失败不影响订单状态更新
    }

      res.json({
        code: 200,
      message: action === 'approve' ? "退款申请已通过" : "退款申请已驳回",
        data: {
        id: order.id,
          orderId: order.orderId,
        productStatus: order.status,
        auditRemark: auditMessage,
        auditTime: new Date().toISOString(),
        auditor: currentAuditor,
        action: action
        },
      });
    } catch (error) {
    console.error('更新售后状态接口catch错误:', error);
      res.status(500).json({
        code: 500,
      message: "更新售后状态失败",
        error: error.message,
      });
    }
});

// 获取售后详情
router.get("/after-sales/:id", async function (req, res, next) {
    try {
    console.log('获取售后详情，ID:', req.params.id);
    
    // 先尝试通过id查询，如果找不到再通过orderId查询
    let order = await YonghuOrderModel.findOne({ id: req.params.id });
    
    // 如果通过id找不到，尝试通过orderId查询
    if (!order) {
      order = await YonghuOrderModel.findOne({ orderId: req.params.id });
    }
  
    
    if (!order) {
        return res.status(404).json({
          code: 404,
        message: "订单不存在",
        });
      }

    // 获取历史记录
    const history = await HistoryModel.findOne({ orderId: order.orderId });
    console.log('查询到的历史记录:', history);
    
    const refundHistory = history?.historyList?.find(h => h.type === '申请退款时间');
    const auditHistory = history?.historyList?.find(h => h.type === '审核时间');
    console.log('退款历史:', refundHistory);
    console.log('审核历史:', auditHistory);
    console.log('退款凭证图片:', refundHistory?.evidencePhotos);

    // 获取商品信息并计算退款金额
    let refundAmount = 0;
    let productDetails = [];
    
    if (order.products && Array.isArray(order.products)) {
      const productIds = order.products.map(p => p.productId);
      console.log('商品ID列表:', productIds);
      
      const goods = await GoodsModel.find({ id: { $in: productIds } });
      console.log('查询到的商品:', goods);
      
      const goodsMap = {};
      goods.forEach(good => {
        goodsMap[good.id] = good;
      });

      order.products.forEach(product => {
        const good = goodsMap[product.productId];
        if (good) {
          const productTotalPrice = good.currentPrice * product.quantity;
          refundAmount += productTotalPrice;
          
          productDetails.push({
            productId: product.productId,
            productName: good.title,
            quantity: product.quantity,
            price: good.currentPrice,
            total: productTotalPrice
        });
      }
      });
    }

    const afterSalesDetail = {
      id: order.id,
      orderId: order.orderId,
      userId: order.userId,
      userName: order.userId,
      refundTime: refundHistory?.time || order.orderTime,
      refundAmount: refundAmount,
      productStatus: order.status,
      refundReason: refundHistory?.reason || '申请退款',
      auditTime: auditHistory?.time,
      auditRemark: auditHistory?.remark,
      auditor: auditHistory?.auditor,
      evidencePhotos: refundHistory?.evidencePhotos || [], // 添加退款凭证图片
      products: productDetails,
      totalQuantity: order.totalQuantity,
      orderTime: order.orderTime,
      deliveryAddress: order.deliveryAddress,
      caption: order.caption,
      createdAt: order.createdAt,
      updatedAt: order.updatedAt
    };

    console.log('返回的详情数据:', afterSalesDetail);

      res.json({
        code: 200,
      message: "获取售后详情成功",
      data: afterSalesDetail,
      });
    } catch (error) {
      console.error('获取售后详情失败:', error);
      res.status(500).json({
        code: 500,
      message: "获取售后详情失败",
        error: error.message,
      });
    }
});

// 用户退款申请接口
router.post("/yonghu/refund-apply", async function (req, res, next) {
  try {
    const { 
      orderId, 
      refundReason, 
      productStatus, 
      evidencePhotos = [],
      userId 
    } = req.body;

    // 验证必填参数
    if (!orderId || !refundReason) {
      return res.status(400).json({
        code: 400,
        message: "订单号和退款原因为必填项",
      });
    }

    // 查找订单
    const order = await YonghuOrderModel.findOne({ orderId: orderId });
    
    if (!order) {
      return res.status(404).json({
        code: 404,
        message: "订单不存在",
      });
    }

    // 检查订单状态是否允许退款
    const allowedStatuses = ['待发货', '待提货', '待评价'];
    if (!allowedStatuses.includes(order.status)) {
      return res.status(400).json({
        code: 400,
        message: "当前订单状态不允许申请退款",
      });
    }

    // 计算退款金额
    let refundAmount = 0;
    if (order.products && Array.isArray(order.products)) {
      const productIds = order.products.map(p => p.productId);
      
      const goods = await GoodsModel.find({ id: { $in: productIds } });
      
      const goodsMap = {};
      goods.forEach(good => {
        goodsMap[good.id] = good;
      });

      order.products.forEach(product => {
        const good = goodsMap[product.productId];
        console.log('商品ID:', product.productId, '商品信息:', good);
        if (good && good.currentPrice && product.quantity) {
          const productTotal = good.currentPrice * product.quantity;
          refundAmount += productTotal;
          console.log('商品价格:', good.currentPrice, '数量:', product.quantity, '小计:', productTotal);
        }
      });
    }

    // 更新订单状态为退款中
    order.status = '退款中';
    order.updatedAt = new Date();
    await order.save();

    // 更新或创建历史记录
    try {
      let history = await HistoryModel.findOne({ orderId: orderId });
      
      if (history) {
        // 更新申请退款时间记录
        const refundTimeIndex = history.historyList.findIndex(item => item.type === '申请退款时间');
        const currentTime = new Date().toISOString();
        
        if (refundTimeIndex !== -1) {
          // 更新现有的申请退款时间记录
          history.historyList[refundTimeIndex] = {
            type: '申请退款时间',
            time: currentTime,
            reason: refundReason,
            productStatus: productStatus,
            evidencePhotos: evidencePhotos
          };
        } else {
          // 如果没有找到申请退款时间点，添加一个新的
          history.historyList.push({
            type: '申请退款时间',
            time: currentTime,
            reason: refundReason,
            productStatus: productStatus,
            evidencePhotos: evidencePhotos
          });
        }
        
        history.updatedAt = new Date();
        await history.save();
      } else {
        // 如果历史记录不存在，创建一个新的
        const historyList = [
          {
            type: '下单时间',
            time: order.orderTime || new Date().toISOString()
          },
          {
            type: '申请退款时间',
            time: new Date().toISOString(),
            reason: refundReason,
            productStatus: productStatus,
            evidencePhotos: evidencePhotos
          },
          {
            type: '审核时间',
            time: '-'
          }
        ];
        
        history = new HistoryModel({
          id: `history_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          userId: userId || order.userId,
          orderId: orderId,
          historyList: historyList,
          createdAt: new Date(),
          updatedAt: new Date()
        });
        await history.save();
      }
    } catch (historyError) {
      console.error('历史记录更新失败:', historyError);
      // 历史记录失败不影响订单状态更新
    }

    res.json({
      code: 200,
      message: "退款申请提交成功",
      data: {
        orderId: order.orderId,
        status: order.status,
        refundReason: refundReason,
        productStatus: productStatus,
        evidencePhotos: evidencePhotos,
        refundAmount: refundAmount
    },
  });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "退款申请提交失败",
      error: error.message,
    });
  }
});

// 用户更新订单状态（如：提货后变为待评价）
router.post('/yonghu/update-order-status', async (req, res) => {
  const { orderId, status } = req.body;
  if (!orderId || !status) {
    return res.json({ code: 400, message: '参数缺失' });
  }
  try {
    const order = await YonghuOrderModel.findOne({ orderId });
    if (!order) {
      return res.json({ code: 404, message: '订单不存在' });
    }
    order.status = status;
    order.updatedAt = new Date();
    await order.save();
    res.json({ code: 200, message: '订单状态更新成功' });
  } catch (err) {
    res.json({ code: 500, message: '服务器错误' });
  }
});

// 批量获取订单历史记录
router.post('/order-history/batch', async function(req, res, next) {
  try {
    const { orderIds } = req.body;
    if (!orderIds || !Array.isArray(orderIds) || orderIds.length === 0) {
      return res.json({ code: 400, message: 'orderIds不能为空' });
    }
    const historyList = await HistoryModel.find({ orderId: { $in: orderIds } });
    console.log('获取到的历史记录:', historyList);
    res.json({
      code: 200,
      message: '获取历史记录成功',
      data: { list: historyList }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '获取历史记录失败',
      error: error.message
    });
  }
});

module.exports = router;
